import 'package:elevator/get/intl_keys.dart';
import 'package:elevator/model/alerm_info.dart';
import 'package:elevator/model/build_detail.dart';
import 'package:elevator/model/build_info.dart';
import 'package:elevator/pages/home/all/detail/detail_view.dart';
import 'package:elevator/pages/search/search_state.dart';
import 'package:elevator/utils/utils_logger.dart';
import 'package:elevator/widgets/globel_widget.dart';
import 'package:elevator/widgets/spirit/spirit_view.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import 'search_logic.dart';

class SearchPage extends StatelessWidget {

  late SearchLogic logic;
  late SearchState state;

  SearchPage({Key? key}) : super(key: key) {
    Get.delete<SearchLogic>();
    logic = Get.put(SearchLogic());
    logic.initData();
    state = logic.state;
  }

  var searchController = TextEditingController();


  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          leading: IconButton(
            icon: const Icon(
              Icons.navigate_before,
              size: 36,
            ),
            onPressed: () {
              Get.back();
            },
          ),
          centerTitle: true,
          title:
              const Image(image: AssetImage("images/logo.png"), width: 100.0),
          actions: [
            IconButton(
              ///icon: const Icon(Icons.person,size: 36,),
              icon: Image.asset("images/person.png"),
              onPressed: () {logic.goToSettingPage();},
            ),
          ],
        ),
        body: Container(
            width: double.infinity,
            height: double.infinity,
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('images/app_bg.png'),
                fit: BoxFit.cover,
              ),
            ),
            child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  Container(
                    ///搜索框
                    margin: const EdgeInsets.fromLTRB(0, 10, 0, 0),
                    height: 48,
                    child: buildSearchInputWidget(context,searchController),
                  ),
                  Container(
                    ///区域选择下拉列表
                    margin: const EdgeInsets.fromLTRB(10, 10, 10, 10),
                    height: 48,
                    color: Colors.white,
                    child: buildSearchByIdView() ,
                  ),
                  Container(
                    ///区域选择下拉列表
                    margin: const EdgeInsets.fromLTRB(10, 0, 10, 10),
                    height: 48,
                    color: Colors.white,
                    child: buildSearchByNameView(),
                  ),
                  Flexible(
                      /// 电梯状态列表布局
                      child: Container(
                        decoration: BoxDecoration(
                          // 背景色
                          border: Border.all(color: Colors.white, width: 0.5),
                          // border
                          borderRadius: BorderRadius.circular((6)), // 圆角
                        ),
                        margin: const EdgeInsets.fromLTRB(4, 0, 4, 4),
                        child:  GetBuilder<SearchLogic>(
                            builder: (SearchLogic controller) {
                              return createLiftListView();
                            }),
                  ))
                ])));

  }


  ///搜索框
  Widget buildSearchInputWidget(BuildContext context,TextEditingController editingController) {
    return  Container(
        alignment: Alignment.center,
        padding: const EdgeInsets.symmetric(horizontal: 8.0),
        child: Autocomplete<BuildInfo>(
            /// 根据用户的输入，构造可选数据的数据源
            optionsBuilder: (TextEditingValue textEditingValue) {
              return state.allBuildList.where((info) => info.buildDetail.buildNumber.contains(textEditingValue.text)).toList();
            },
            /// 自定义可选数据列表框的显示内容和样式等
            ///   options 是 optionsBuilder 筛选出的可选数据
            ///   onSelected 用于选中某一项时触发回调
            optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<BuildInfo> onSelected, Iterable<BuildInfo> options) {
              return Align(
                alignment: Alignment.topLeft,
                child: Material(
                  child: ListView.builder(
                    itemBuilder: (BuildContext context, int index) {
                      var buildInfo = options.elementAt(index);
                      return Column(
                          children: [
                            ListTile(
                              onTap: () {
                                /// 回调，Autocomplete 的 onSelected() 会收到此回调
                                onSelected.call(buildInfo);
                              },
                              title: Text(buildInfo.buildDetail.buildNumber),
                            ),
                            const Divider()
                          ],);
                    },
                    itemCount: options.length,
                  ),
                ),
              );
            },

            /// 从可选数据列表框中选中某一项后，可以通过这里格式化选中的内容
            displayStringForOption: (BuildInfo obj) => obj.buildDetail.buildNumber,
            /// 自定义 Autocomplete 的样式和行为等
            fieldViewBuilder: (BuildContext context, TextEditingController textEditingController, FocusNode focusNode, VoidCallback onFieldSubmitted) {
              return TextFormField(
                controller: textEditingController,
                focusNode: focusNode,
                onFieldSubmitted: (String value) {
                  /// 调用 onFieldSubmitted() 之后才能走到 Autocomplete 的 optionsBuilder()
                  onFieldSubmitted();
                },
                /// 用于定义 Autocomplete 的样式
                decoration: const InputDecoration(
                  filled: true,
                  fillColor: Colors.white,
                  hintText: "",
                  suffixIcon: Icon(Icons.search),
                  focusedBorder: OutlineInputBorder(
                    ///用来配置边框的样式
                    borderSide: BorderSide(
                      ///设置边框的颜色
                      color: Colors.orange,
                      ///设置边框的粗细
                      width: 1,
                    ),
                  ),
                  border: OutlineInputBorder(
                    ///用来配置边框的样式
                    borderSide: BorderSide(
                      ///设置边框的颜色
                      color: Colors.white,
                      ///设置边框的粗细
                      width: 1,
                    ),
                  ),
                ),
              );
            },

            /// 从可选数据列表框中选中某一项时的回调
            onSelected: (BuildInfo buildInfo) {
              debugPrint('onSelected: ${buildInfo.toString()}');
              FocusScope.of(context).unfocus();
              logic.onSelectBuildInfo(buildInfo);
            },
          ));
  }

  Widget buildSearchByIdView() {
    return Row(mainAxisAlignment: MainAxisAlignment.start, children: [
      Flexible(
          flex: 2,
          fit:FlexFit.tight,
          child: Container(
            decoration: const BoxDecoration(
              // 背景色
              border: Border(
                top: BorderSide.none,
                right: BorderSide(width: 1, color: Colors.black),
                bottom: BorderSide.none,
                /// 无边框，等同于 BorderSide(width: 0.0, style: BorderStyle.none);
                left: BorderSide.none,
              ),
            ),
            child: Center(child:Text(IntlKeys.subName.tr, style: TextStyle(fontSize: 20))),
          )),
       Flexible(
          flex: 3,
          fit:FlexFit.tight,
          child:Obx(() =>
              Padding(padding:const EdgeInsets.fromLTRB(10, 0, 0, 0),child:DropdownButton<BuildDetail>(
                  value: state.selectBuildDetail.value,
                  onChanged: (v) {
                    logic.onSelectBuildZoneChanged(v!);
                  },
                  isExpanded:true,
                  underline: const SizedBox(
                    height: 0.0,
                    width: double.infinity,
                  ),
                  items: state.buildDetailList.value.map((e) {
                    return DropdownMenuItem<BuildDetail>(
                        value: e, child: Text(e.buildSubZoneCn));
                  }).toList()
          )) )
      )]);

  }

  Widget buildSearchByNameView() {
    return Row(mainAxisAlignment: MainAxisAlignment.start, children: [
      Flexible(
          flex: 2,
          fit:FlexFit.tight,
          child: Container(
            decoration: const BoxDecoration(
              // 背景色
              border: Border(
                top: BorderSide.none,
                right: BorderSide(width: 1, color: Colors.black),
                bottom: BorderSide.none,
                /// 无边框，等同于 BorderSide(width: 0.0, style: BorderStyle.none);
                left: BorderSide.none,
              ),
            ),
            child: Center(child:Text(IntlKeys.areaNo.tr, style: TextStyle(fontSize: 20))),
          )),
      Flexible(
          flex: 3,
          fit:FlexFit.tight,
          child:Obx(() =>
              Padding(padding:const EdgeInsets.fromLTRB(10, 0, 0, 0),child:DropdownButton<BuildInfo>(
                  value: state.selectBuildInfo.value,
                  onChanged: (v) {
                    logic.onSelectBuildChanged(v!);
                  },
                  isExpanded:true,
                  underline: Container(
                    height: 0.0,
                  ),
                  items: state.buildList.value.map((e) {
                    return DropdownMenuItem<BuildInfo>(
                        value: e, child: Text(e.getTag()));
                  }).toList()
              )) )
      )]);

  }


  ///中间电梯信息列表
  createLiftListView(){
    return Obx(() => ListView.builder(
      itemCount: state.liftList.length,
      itemBuilder: (context, index) {
        var data = logic.state.liftList.value[index];
        var alarmList = data.alermList;
        return Column(
          children: [
            spaceHeight(height: 10),
            SpiritComponent(
              onTap: () {
                logd('onTap');
                Get.toNamed("/lift_detail",arguments: {"buildInfo":state.selectBuildInfo.value, "liftInfo":data,"psAuth":state.psAuth!,"user":state.user});
              },
              onLongPress: () {
                logd('onLongPress');
              },
              liftType: data.liftType,
              liftOpenType:data.liftOpenType,
              curStates: data.currentState,
              lLeftText: data.liftName,
              lRightText: data.currentAddr,
              widgets: getAlermInfoWidgets(alarmList),
            ),
            spaceHeight(height: 10),
          ],
        );
      },
    ));
  }
}
